<template>
  <transition name="down">
    <div
      v-show="isVisible"
      class="min-w-[420px] fixed top-[20px] left-[50%] translate-x-[-50%] z-50 flex items-center px-3 py-1.5 rounded-sm border cursor-pointer"
      :class="styles[type].containerClass"
    >
      <z-svg-icon
        :name="styles[type].icon"
        :fillClass="styles[type].fillClass"
        class="h-1.5 w-1.5 mr-1.5"
      ></z-svg-icon>
      <span class="text-sm" :class="styles[type].textClass">{{ content }}</span>
    </div>
  </transition>
</template>

<script setup>
import { MESSAGE_TYPES } from '@/constants/message'
import zSvgIcon from '../svg-icon/index.vue'
import { onMounted, ref } from 'vue'

const props = defineProps({
  /**
   * 消息类型
   */
  type: {
    type: String,
    required: true,
    validator: (value) => {
      const result = MESSAGE_TYPES.includes(value)
      if (!result) {
        throw new Error('type 类型错误')
      }
      return result
    }
  },
  /**
   * 消息内容
   */
  content: {
    type: String,
    required: true
  },
  /**
   * 消息持续时间
   */
  duration: {
    type: Number,
    default: 3000
  },
  /**
   * 关闭回调函数
   */
  destory: {
    type: Function
  }
})

/**
 * 消息类型对应样式
 */
const styles = {
  warn: {
    icon: 'warn',
    fillClass: 'fill-warn-300',
    textClass: 'text-warn-300',
    containerClass:
      'bg-warn-100 border-warn-200 hover:shadow-lg hover:shadow-warn-100'
  },
  error: {
    icon: 'error',
    fillClass: 'fill-error-300',
    textClass: 'text-error-300',
    containerClass:
      'bg-error-100 border-error-200 hover:shadow-lg hover:shadow-error-100'
  },
  success: {
    icon: 'success',
    fillClass: 'fill-success-300',
    textClass: 'text-success-300',
    containerClass:
      'bg-success-100 border-success-200 hover:shadow-lg hover:shadow-success-100'
  }
}

/**
 * 是否显示
 */
const isVisible = ref(false)

// 关闭动画时间
const animDuration = '0.5s'

/**
 * 组件挂载后显示消息
 */
onMounted(() => {
  isVisible.value = true
  setTimeout(() => {
    isVisible.value = false
    // 延迟关闭消息，防止动画时间不足
    setTimeout(() => {
      if (props.destory) {
        props.destory()
      }
    }, parseFloat(animDuration.replace('0.', '').replace('s', '')) * 100)
  }, props.duration)
})
</script>

<style lang="scss" scoped>
.down-enter-active,
.down-leave-active {
  transition: all v-bind(animDuration);
}

.down-enter-from,
.down-leave-to {
  opacity: 0;
  transform: translate3d(-50%, -10px, 0);
}
</style>
